package com.learn.xxl.job.exception;


import com.google.common.collect.Maps;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;

/**
 * 全局异常处理
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2024/5/1 21:37
 * @updateUser:     MI
 * @updateTime:     2024/5/1 21:37
 * @updateRemark:   修改内容
 * @version:        v1.0
 */
@Slf4j
@ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理 json 请求体调用接口校验失败抛出的异常
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = Throwable.class)
    public Object handleValidException(Throwable ex, HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        if (ex instanceof BindException) {

            // 处理 form data方式调用接口校验失败抛出的异常
            BindingResult bindingResult = ((BindException) ex).getBindingResult();
            String message = null;
            if (bindingResult.hasErrors()) {
                FieldError fieldError = bindingResult.getFieldError();
                if (fieldError != null) {
                    message = fieldError.getField() + fieldError.getDefaultMessage();
                }
            }
            map.put("msg", message);
        }
        return map;
    }

}
